<template>
  <div>
    <!-- 头部查询、添加区域 -->
    <el-form ref="form" style="margin-left: 20px">
      <el-form-item>
        <el-input
          v-model="roleName"
          placeholder="角色名称"
          style="width: 200px; margin-right: 10px"
        ></el-input>
        <el-button type="primary" icon="el-icon-search" @click="queryRole"
          >查询</el-button
        >
        <el-button @click="clearRoleName">清空</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="centerDialogVisible = true"
          >添加</el-button
        >
        <el-button
          type="danger"
          :disabled="isDelete"
          @click="delDialogVisible = true"
          >批量删除</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 显示角色数据的表格 -->
    <!--  @selection-change="handleSelectionChange" -->
    <el-table
      v-loading="loading"
      stripe
      style="width: 90%; margin-left: 20px"
      border
      :data="roleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center">
      </el-table-column>
      <el-table-column type="index" label="序号" width="80" align="center">
      </el-table-column>
      <el-table-column prop="roleName" label="角色名称" width="500">
        <template slot-scope="{ row }">
          <span v-show="!row.isEdit">{{ row.roleName }}</span>
          <div v-show="row.isEdit">
            <el-input
              v-model="row.updateRoleName"
              size="mini"
              style="width: 385px; margin-right: 18px"
            ></el-input>
            <el-button
              type="warning"
              icon="el-icon-refresh"
              size="mini"
              @click="cancelUpdateRole(row)"
              >取消</el-button
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" align="center">
        <template slot-scope="{ row }">
          <router-link
            :to="{
              name: 'RoleAuth',
              // params参数
              params: {
                id: row.id
              },
              // query参数
              query: {
                roleName: row.roleName
              }
            }"
            style="margin-right: 10px"
          >
            <el-button
              type="info"
              icon="el-icon-info"
              size="mini"
              title="分配权限"
            ></el-button>
          </router-link>
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            title="修改角色"
            @click="updateRole(row)"
            v-show="!row.isEdit"
          ></el-button>
          <el-button
            type="primary"
            icon="el-icon-check"
            size="mini"
            title="确认"
            v-show="row.isEdit"
            @click="affirmUpdate(row)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            title="删除角色"
            @click="removeRole(row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      :current-page="page"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="limit"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="roleInfo.total"
      style="margin: 20px 0 0 10px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="centerDialogVisible" width="32%">
      <p>请输入新名称</p>
      <el-input v-model="newRoleName" style="margin-bottom: 20px"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAddRole" size="mini">取消</el-button>
        <el-button type="primary" @click="addRole" size="mini">确定</el-button>
      </span>
      <!-- 批量删除对话框 -->
    </el-dialog>
    <!-- 批量删除角色对话框 -->
    <el-dialog title="提示" :visible.sync="delDialogVisible" width="30%">
      <div class="warnBox">
        <span class="iconfont icon-tixingshixin warn"></span>
        <span>此操作将永久删除该记录，是否继续?</span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelBatchRemove" size="mini">取 消</el-button>
        <el-button type="primary" @click="batchDelete" size="mini"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 引入深拷贝函数
import cloneDeep from "lodash/cloneDeep";
import { mapState } from "vuex";
export default {
  name: "Role",
  data() {
    return {
      // 控制删除按钮的禁用效果
      isDelete: true,
      // 当前页
      page: 1,
      // 每页显示的条数
      limit: 5,
      // 角色姓名
      roleName: "",
      // 加载效果
      loading: true,
      // 控制添加角色对话框的显示与隐藏
      centerDialogVisible: false,
      // 添加的角色名称
      newRoleName: "",
      // 要批量删除的角色id列表
      deleteRoleList: [],
      // 控制批量删除对话框的显示与隐藏
      delDialogVisible: false,
      // 修改文本框存储的角色名称
      roleName: "",
    };
  },
  computed: {
    ...mapState("role", ["roleInfo"]),
    roleList() {
      // 临时变量，仓库没传递数据过来前，赋值为空数组
      const list = this.roleInfo.items || [];
      // 遍历添加一个标记，用来判断是否进行修改
      list.forEach((elm) => {
        this.$set(elm, "isEdit", false);
        this.$set(elm, "updateRoleName", elm.roleName);
      });
      return this.roleInfo.items || [];
    },
  },
  methods: {
    // 获取角色信息
    async getRoleInfo() {
      this.loading = true;
      const dataList = {
        page: this.page,
        limit: this.limit,
        roleName: this.roleName,
      };
      try {
        await this.$store.dispatch("role/getRoleInfo", dataList);
        this.loading = false;
      } catch (error) {
        this.$message({
          message: "加载角色列表失败",
          type: "error",
        });
      }
    },
    // 每页条数发生改变时的回调
    handleSizeChange(limit) {
      this.limit = limit;
      // 重新调用获取角色信息
      this.getRoleInfo();
    },
    // 当前页发生改变时的回调
    handleCurrentChange(page) {
      this.page = page;
      // 重新调用获取角色信息
      this.getRoleInfo();
    },
    // 点击查询按钮，查询角色信息
    queryRole() {
      this.getRoleInfo();
    },
    // 清空roleName，重新发送获取角色信息
    clearRoleName() {
      this.roleName = "";
      this.getRoleInfo();
    },
    // 取消添加新角色
    cancelAddRole() {
      this.$message({
        message: "取消添加",
        type: "warning",
      });
      // 清空input
      this.newRoleName = "";
      // 关闭对话框
      this.centerDialogVisible = false;
    },
    // 确认添加角色
    async addRole() {
      // 判断是否为空
      if (!this.newRoleName) {
        this.$message({
          message: "名称不能为空！",
          type: "warning",
        });
        return;
      }
      try {
        // 发送添加新角色的action
        await this.$store.dispatch("role/getAddRole", {
          roleName: this.newRoleName,
        });
        this.$message({
          message: "添加成功",
          type: "success",
        });
        // 关闭对话框
        this.centerDialogVisible = false;
        // 清空input
        this.newRoleName = "";
        // 回到第一页
        this.page = 1;
        // 重新发送获取角色列表
        this.getRoleInfo();
      } catch (error) {
        this.$message({
          message: "添加失败",
          type: "error",
        });
      }
    },
    // 选择框发生改变时的回调
    handleSelectionChange(selectionRoleList) {
      if (selectionRoleList.length < 1) {
        // 没选择任何角色，批量删除按钮禁用
        this.isDelete = true;
        // 清空要删除的角色id列表
        this.deleteRoleList = [];
      } else {
        // 选择了角色，批量删除按钮解除禁用
        this.isDelete = false;
        // 将选择出来的角色id列表赋值给deleteRoleList
        this.deleteRoleList = selectionRoleList.map((elm) => elm.id);
      }
    },
    // 批量删除
    async batchDelete() {
      // 隐藏对话框
      this.delDialogVisible = false;
      try {
        // 派发批量删除的actions
        await this.$store.dispatch("role/batchRemove", this.deleteRoleList);
        this.$message({
          message: "删除成功",
          type: "success",
        });
        // 让角色列表页重新回到第一页
        this.page = 1;
        // 重新调用获取角色列表数据的函数，重新渲染
        this.getRoleInfo();
      } catch (error) {
        this.$message({
          message: "删除失败",
          type: "error  ",
        });
      }
    },
    // 取消批量删除
    cancelBatchRemove() {
      // 关闭对话框
      this.delDialogVisible = false;
      // 提示信息
      this.$message({
        message: "取消删除",
        type: "info",
      });
    },
    // 点击修改角色按钮，将修改文本框显示出来
    updateRole(row) {
      row.isEdit = true;
    },
    // 取消修改角色
    cancelUpdateRole(row) {
      row.updateRoleName = row.roleName;
      row.isEdit = false;
      this.$message({
        message: "取消角色修改",
        type: "warning",
      });
    },
    // 确认修改
    async affirmUpdate(row) {
      const role = cloneDeep(row);
      if (!role.updateRoleName) {
        this.$message({
          message: "角色名称不能为空",
          type: "warning",
        });
        return;
      }
      // 将修改后的角色名赋值到roleName上
      role.roleName = role.updateRoleName;
      try {
        // 派发actions
        await this.$store.dispatch("role/updateRoleInfo", role);
        // 提示信息
        this.$message({
          message: "修改成功",
          type: "success",
        });
        // 将文本框隐藏
        row.isEdit = false;
        // 重新获取角色列表
        this.getRoleInfo();
      } catch (error) {
        this.$message({
          message: "修改失败",
          type: "error",
        });
      }
    },
    // 删除角色弹框的回调
    removeRole(row) {
      this.$confirm(`确定删除'${row.roleName}'吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            // 派发删除的actions
            await this.$store.dispatch("role/removeRole", row.id);
            // 提示
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            // 判断当前页的数据是否是最后一条，是的话，要跳到上一页
            if (this.roleList.length < 1) {
              this.page = this.page - 1;
            }
            // 重新获取角色列表
            this.getRoleInfo();
          } catch (error) {
            this.$message({
              type: "error",
              message: "删除失败!",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  mounted() {
    // 页面挂载完毕，获取角色信息
    this.getRoleInfo();
  },
};
</script>

<style>
.el-dialog__body {
  padding-top: 0px;
  padding-bottom: 0px;
}
.warnBox {
  display: flex;
  align-items: center;
}
.warn {
  margin-right: 10px;
  font-size: 20px;
  color: #e6a23c;
}
</style>